# -*- coding: utf-8 -*-

"""
  Support UNIX daemon.

  author sato.tatsuma
"""

import sys
import time
from settings import dns_list
from daemon import Daemon
from ddns_thread import DdnsThread

class DdnsDaemon(Daemon):
  """
  """
  def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
    Daemon.__init__(self, pidfile, stdin, stdout, stderr)
    self.settings = dns_list
    self.threads = []

  def __del__(self):
    for thread in self.threads:
      thread.join()

  def run(self):
    """
    Override method.
    run() will called by Daemon class when daemon process started.
    """
    if not self.settings:
      # Not loaded settings.
      if not self.load_settings():
        print 'exit load_settings()'
        self.stop()

      if not self.check_settings():
        print 'exit check_settings'
        self.stop()

    for setting in self.settings:
      # Create threads.
      ddns_thread = DdnsThread(setting)
      ddns_thread.start()
      self.threads.append(ddns_thread)

    # Main loop.
    count = 0
    while True:
      # Sleep large time.
      # Main process run as thread,
      # So this process only flush log streams.
      time.sleep(60)
      for f in sys.stdout, sys.stderr:
        f.flush()

  def check_settings(self):
    """
    Check settings.
    Requires:
      'domain', 'host', 'password', 'request_domain', 'request_url'
    """
    for setting in self.settings:
      try:
        setting['domain']
        setting['domain_host']
        setting['password']
        setting['request_domain']
        setting['request_url']
      except KeyError, e:
        sys.stderr.write("Config file error.\n")
        return False

      try:
        setting['interval']
        # In settings.yaml set as minutes.
        # But time.sleep() is spedified by seconds.
        # So convert to seconds.
        setting['interval'] *= 60
      except KeyError:
        print "interval not set. Use default value."
        setting['interval'] = 60 * 60

      try:
        if not setting['force_update']:
          # Set False when not set force_update value.
          setting['force_update'] = False
      except KeyError:
        print "force_update not set. Use default value."
        setting['force_update'] = False

      try:
        if not setting['update_ipaddress']:
          # Set True when not set update_ipaddress value.
          setting['update_ipaddress']
      except KyeError:
        print "update_ipaddress not set. Use default value."
        setting['update_ipaddress']


    return True
